<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>支付 - 鲜时蔬</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <!-- 引入vue-qriously生成二维码 -->
    <script src="../../js/vue-qriously.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .container {
            width: 1140px;
            margin: 0 auto;
            padding: 0 15px;
        }

        @media (max-width: 1199px) {
            .container {
                width: 960px;
            }
        }

        @media (max-width: 991px) {
            .container {
                width: 720px;
            }
        }

        @media (max-width: 767px) {
            .container {
                width: 100%;
            }
        }

        /* 导航栏 */
        .header {
            background: #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 20px;
            font-weight: bold;
            color: #27ae60;
            text-decoration: none;
        }

        .logo i {
            margin-right: 8px;
        }

        .nav {
            display: flex;
        }

        .nav a {
            margin: 0 15px;
            text-decoration: none;
            color: #666;
            font-size: 14px;
            padding: 5px 0;
        }

        .nav a.active {
            color: #27ae60;
            border-bottom: 2px solid #27ae60;
        }

        .user-actions {
            display: flex;
            align-items: center;
            position: relative;
        }

        .user-actions button {
            margin-left: 15px;
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
        }

        .user-actions button i {
            margin-right: 5px;
        }

        /* 用户信息下拉菜单 */
        .user-info {
            position: relative;
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #27ae60;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            font-size: 14px;
        }

        .user-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            padding: 5px 0;
            min-width: 120px;
            z-index: 10;
            margin-top: 5px;
            display: none;
        }

        .user-dropdown.show {
            display: block;
        }

        .user-dropdown-item {
            padding: 8px 15px;
            font-size: 14px;
            color: #606266;
            cursor: pointer;
        }

        .user-dropdown-item:hover {
            background-color: #f5f7fa;
            color: #27ae60;
        }

        /* 主内容区 */
        .main {
            padding-top: 80px;
            padding-bottom: 50px;
        }

        /* 页面标题 */
        .page-title {
            font-size: 24px;
            color: #333;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* 支付内容 */
        .pay-content {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        .order-summary {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }

        .summary-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
        }

        .order-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px dashed #eee;
        }

        .item-info {
            flex: 3;
        }

        .item-price {
            flex: 1;
            text-align: right;
        }

        .order-total {
            display: flex;
            justify-content: space-between;
            font-size: 18px;
            font-weight: bold;
            margin: 20px 0;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }

        .total-amount {
            color: #e74c3c;
        }

        .pay-info {
            text-align: center;
            margin: 30px 0;
        }

        .pay-amount {
            font-size: 20px;
            margin: 15px 0;
        }

        .pay-amount span {
            color: #e74c3c;
            font-weight: bold;
            font-size: 28px;
        }

        .pay-button {
            background-color: #e74c3c;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 15px 40px;
            font-size: 18px;
            cursor: pointer;
            margin: 20px 0;
        }

        .pay-button:hover {
            background-color: #c0392b;
        }

        .pay-button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        .qrcode-container {
            margin: 20px 0;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .qrcode-status {
            margin-top: 15px;
            font-size: 16px;
        }

        .success-message {
            color: #27ae60;
            font-size: 18px;
            font-weight: bold;
            margin: 20px 0;
            text-align: center;
        }

        .success-message i {
            font-size: 64px;
            display: block;
            margin-bottom: 15px;
        }

        .back-button {
            background-color: #27ae60;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 12px 30px;
            font-size: 16px;
            cursor: pointer;
            margin: 20px 0;
        }

        .back-button:hover {
            background-color: #219653;
        }

        /* 页脚 */
        .footer {
            background: #333;
            color: #fff;
            padding: 30px 0;
            margin-top: 50px;
        }

        .footer-content {
            text-align: center;
            font-size: 14px;
        }

        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 50px;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 导航栏 -->
    <header class="header">
        <div class="container">
            <div class="header-content">
                <a href="index.html" class="logo">
                    <i class="el-icon-shopping-bag"></i>
                    <span>鲜时蔬</span>
                </a>
                <nav class="nav">
                    <a href="index.html">首页</a>
                    <a href="vegetables.html">蔬菜列表</a>
                    <a href="contact.html">联系我们</a>
                </nav>
                <div class="user-actions">
                    <!-- 根据登录状态显示不同内容 -->
                    <template v-if="isLoggedIn">
                        <div class="user-info" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
                            <div class="user-avatar">
                                {{ userInfo.nickName ? userInfo.nickName.charAt(0) : userInfo.userName.charAt(0) }}
                            </div>
                            <span>{{ userInfo.nickName || userInfo.userName }}</span>
                            <div class="user-dropdown" :class="{ 'show': showDropdown }">
                                <div class="user-dropdown-item" @click="goToPersonalCenter">个人中心</div>
                                <div class="user-dropdown-item" @click="logout">退出登录</div>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <button @click="goToLogin">
                            <i class="el-icon-user"></i> 登录
                        </button>
                    </template>
                    <button @click="goToCart">
                        <i class="el-icon-shopping-cart"></i> 购物车({{ cartCount }})
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="main">
        <div class="container">
            <div class="page-title">
                <h1>订单支付</h1>
            </div>

            <div class="pay-content">
                <div v-if="loading" class="loading">
                    <el-spinner style="margin: 50px auto;"></el-spinner>
                    <p>正在加载订单信息...</p>
                </div>

                <div v-else>
                    <div v-if="!paymentSuccess">
                        <!-- 订单摘要 -->
                        <div class="order-summary">
                            <div class="summary-title">订单信息</div>
                            <div class="order-item" v-for="item in cartItems" :key="item.cartId">
                                <div class="item-info">
                                    <div>{{ item.product.productName }}</div>
                                    <div style="font-size: 14px; color: #999;">数量: {{ item.quantity }}</div>
                                </div>
                                <div class="item-price">¥{{ (item.product.price * item.quantity).toFixed(2) }}</div>
                            </div>
                            <div class="order-total">
                                <span>订单总额:</span>
                                <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
                            </div>
                            <div style="font-size: 14px; color: #999;">
                                订单编号: {{ orderNo }}
                            </div>
                        </div>

                        <!-- 支付信息 -->
                        <div class="pay-info">
                            <div class="pay-amount">
                                支付金额: <span>¥{{ totalAmount.toFixed(2) }}</span>
                            </div>
                            <button class="pay-button" @click="initiatePayment" :disabled="isPaying">
                                {{ isPaying ? '正在生成支付二维码...' : '立即支付' }}
                            </button>
                        </div>

                        <!-- 支付二维码弹窗 -->
                        <el-dialog
                                title="微信扫码支付"
                                :visible.sync="showQRDialog"
                                width="400px"
                                :before-close="handleClose">
                            <div class="qrcode-container">
                                <div style="margin-bottom: 15px;">支付金额: ¥{{ totalAmount.toFixed(2) }}</div>
                                <qriously v-if="codeUrl" :value="codeUrl" :size="256" />
                                <div class="qrcode-status">
                                    订单状态: {{ payStatus }}
                                </div>
                                <div v-if="payStatus === '支付成功'" class="success-message">
                                    支付成功！
                                </div>
                            </div>
                        </el-dialog>
                    </div>

                    <!-- 支付成功 -->
                    <div v-else>
                        <div class="success-message">
                            <i class="el-icon-success"></i>
                            <h2>支付成功！</h2>
                            <p>订单编号: {{ orderNo }}</p>
                            <p>支付金额: ¥{{ totalAmount.toFixed(2) }}</p>
                        </div>
                        <div style="text-align: center;">
                            <button class="back-button" @click="goToOrderList">
                                查看订单详情
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <p>© 2025 鲜时蔬 版权所有 | 京ICP备12345678号</p>
            </div>
        </div>
    </footer>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                showDropdown: false,
                isLoggedIn: false,
                userInfo: {},
                loading: true,
                cartItems: [],
                totalAmount: 0,
                cartCount: 0,
                orderNo: '',
                isPaying: false,
                showQRDialog: false,
                codeUrl: '',
                payStatus: '等待支付',
                paymentSuccess: false,
                timer: null
            }
        },
        mounted() {
            this.checkLoginStatus();
            this.loadCartData();
        },
        beforeDestroy() {
            if (this.timer) {
                clearInterval(this.timer);
            }
        },
        methods: {
            // 检查登录状态
            checkLoginStatus() {
                axios.get('/vegetablemarketexpress/user/checkLoginStatus', {withCredentials: true})
                    .then(response => {
                        if (response.data.code === 200 && response.data.data) {
                            this.isLoggedIn = true;
                            this.userInfo = response.data.data;
                        } else {
                            this.isLoggedIn = false;
                            this.userInfo = {};
                            // 未登录跳转到登录页面
                            window.location.href = 'login.html';
                        }
                    })
                    .catch(error => {
                        console.error('检查登录状态失败:', error);
                        this.isLoggedIn = false;
                        // 出错跳转到登录页面
                        window.location.href = 'login.html';
                    });
            },

            // 加载购物车数据
            loadCartData() {
                this.loading = true;

                // 使用已有的 getCartDetails 接口
                axios.get('/vegetablemarketexpress/cart/getCartDetails', {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.cartItems = response.data.data || [];
                            this.calculateTotals();

                            // 创建订单
                            if (this.cartItems.length > 0) {
                                this.createOrder();// 创建订单
                            }
                        } else {
                            this.cartItems = [];
                            this.calculateTotals();
                        }
                    })
                    .catch(error => {
                        console.error('加载购物车数据失败:', error);
                        this.$message.error('网络错误，加载购物车数据失败');
                        this.cartItems = [];
                        this.calculateTotals();
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 计算总金额和总数量
            calculateTotals() {
                this.totalAmount = 0;
                this.cartCount = 0;

                this.cartItems.forEach(item => {
                    const price = parseFloat(item.product.price) || 0;
                    const quantity = parseInt(item.quantity) || 0;
                    this.totalAmount += price * quantity;
                    this.cartCount += quantity;
                });
            },

            // 创建订单
            createOrder() {
                // 生成订单号
                this.orderNo = 'ORDER' + new Date().getTime();

                // 构造订单数据
                const orderData = {
                    orderNo: this.orderNo,
                    userId: this.userInfo.userId,
                    totalAmount: this.totalAmount,
                    status: 0, // 0-待支付
                    orderItems: this.cartItems.map(item => ({
                        productId: item.product.productId,
                        orderQuantity: item.quantity,
                        salePrice: item.product.price,
                        productName: item.product.productName,
                        purchasePrice: item.product.price,
                        amount: item.product.price * item.quantity
                    }))
                };

                // 调用后端创建订单接口
                axios.post('/vegetablemarketexpress/order/createOrder', orderData, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            console.log('订单创建成功');
                        } else {
                            this.$message.error('订单创建失败');
                        }
                    })
                    .catch(error => {
                        console.error('创建订单失败:', error);
                        this.$message.error('网络错误，创建订单失败');
                    });
            }
            ,

            // 发起支付
            initiatePayment() {
                if (this.cartItems.length === 0) {
                    this.$message.warning('购物车为空，无法支付');
                    return;
                }

                this.isPaying = true;
                this.payStatus = '等待支付';
                this.codeUrl = '';

                // 构造订单信息，使用订单编号替代原来的orderNum
                const order = {

                    orderNo: this.orderNo,
                    totalAmount: this.totalAmount,
                    remark: "鲜时蔬购物订单"
                };

                // 请求支付二维码
                axios.post('/vegetablemarketexpress/order/getNativeCodeUrl', order, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.codeUrl = response.data.data.code_url;
                            this.showQRDialog = true;
                            this.startQueryPayStatus();
                        } else {
                            this.$message.error('获取支付二维码失败');
                        }
                    })
                    .catch(error => {
                        console.error('发起支付失败:', error);
                        this.$message.error('网络错误，发起支付失败');
                    })
                    .finally(() => {
                        this.isPaying = false;
                    });
            },


            // 开始轮询支付状态
            startQueryPayStatus() {
                // 清除之前的定时器
                if (this.timer) {
                    clearInterval(this.timer);
                }

                // 每3秒查询一次支付状态
                this.timer = setInterval(() => {
                    this.queryPayStatus();
                }, 3000);
            },

            // 查询支付状态
            queryPayStatus() {
                if (!this.orderNo) return;

                axios.get('/vegetablemarketexpress/order/getPayStatus/' + this.orderNo, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.payStatus = response.data.data.trade_state_desc;

                            if (this.payStatus === '支付成功') {
                                this.paymentSuccess = true;
                                this.showQRDialog = false;
                                clearInterval(this.timer);
                                this.updateOrderStatus();
                                this.clearCart();
                            }
                        }
                    })
                    .catch(error => {
                        console.error('查询支付状态失败:', error);
                    });
            },


            // 更新订单状态
            updateOrderStatus() {
                const updateData = {
                    orderNo: this.orderNo,
                    status: 1 // 1-已支付
                };

                axios.post('/vegetablemarketexpress/order/updateStatus', updateData, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            console.log('订单状态更新成功');
                        } else {
                            console.error('订单状态更新失败');
                        }
                    })
                    .catch(error => {
                        console.error('更新订单状态失败:', error);
                    });
            },

            // 清空购物车
            clearCart() {
                const deletePromises = this.cartItems.map(item => {
                    return axios.delete('/vegetablemarketexpress/cart/removeFromCart', {
                        params: { cartId: item.cartId },
                        withCredentials: true
                    });
                });

                Promise.all(deletePromises)
                    .catch(error => {
                        console.error('清空购物车失败:', error);
                    });
            },

            // 关闭对话框
            handleClose(done) {
                this.$confirm('确认关闭支付窗口？')
                    .then(_ => {
                        done();
                        if (this.timer) {
                            clearInterval(this.timer);
                        }
                    })
                    .catch(_ => {});
            },

            // 查看订单详情
            goToOrderList() {
                window.location.href = 'personalCenter.html#orders';
            },

            // 跳转到个人中心
            goToPersonalCenter() {
                window.location.href = '/vegetablemarketexpress/html/front/personalCenter.html';
            },

            // 退出登录
            logout() {
                axios.get('/vegetablemarketexpress/user/logout', { withCredentials: true })
                    .then(response => {
                        if (response.data.code === 200) {
                            this.isLoggedIn = false;
                            this.userInfo = {};
                            this.showDropdown = false;
                            this.$message.success('退出登录成功');
                            window.location.href = 'index.html';
                        } else {
                            this.$message.error('退出登录失败');
                        }
                    })
                    .catch(error => {
                        console.error('退出登录失败:', error);
                        this.$message.error('退出登录失败');
                    });
            },

            goToLogin() {
                window.location.href = 'login.html';
            },

            goToCart() {
                window.location.href = 'cart.html';
            }
        }
    });
</script>
</body>
</html>
